package com.example.wn.sdu_notification;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {
    private static final String FILE_NAME = "listview_message";

    RefreshableView refreshableView;
    ListView listView;
    ArrayAdapter<String> adapter;
    static ArrayList<String> list = new ArrayList<>();
    ArrayList<String> timelist = new ArrayList<>();
    static Document doc ;
    static Elements newstitle;
    Elements time;
    static int ps;
    ObjectInputStream fis;
    ObjectOutputStream fos;
    static boolean sd;
    //文件名
    private static final String FILE_NAME2 = "listview_href";
    ObjectInputStream fis1;
    ObjectOutputStream fos2;
    static ArrayList<String> hreflist;
    BidirSlidingLayout bidirSldingLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);

        doc = new Document("");
        newstitle = new Elements();time = new Elements();

        try {
            CreateMessageText();
            CreateHrefText();
        } catch (IOException e) {
            e.printStackTrace();
        }

        list = readInMessage();
        hreflist = readInHref();

        listView = (ListView) findViewById(R.id.list_view);
        adapter = new ArrayAdapter<String>(this, R.layout.listview_item,list);
        listView.setAdapter(adapter);
        final Intent intent = new Intent(this,TotalNotification.class);
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                while (true) {
                    try{
                        doc = Jsoup.connect("http://www.youth.sdu.edu.cn/news/list.jsp").get();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    newstitle = doc.select("div.content_all>ul>li>a");
                    time = doc.select("div.content_all>ul>li>span");
                    if (newstitle.size() != 0 && time.size() != 0) {
                        if (list.size() == 0) {
                            for (int i = 0; i < 30; i++) {
                                timelist.add(i, time.get(i).text());
                                list.add(i, newstitle.get(i).text()+"\n"+timelist.get(i)+"\n");
                            }
                            writeOutMessage();
                        }
                        else {
                            for (int i = 0; i < 30; i++) {
                                list.remove(0);
                                if(timelist.size() != 0) {
                                    timelist.remove(0);
                                }
                            }
                            for (int i = 0; i < 30; i++) {
                                timelist.add(i, time.get(i).text());
                                list.add(i, newstitle.get(i).text()+"\n"+timelist.get(i));
                            }
                            writeOutMessage();
                        }
                    }
                    else if (newstitle.size() == 0) {
                        continue;
                    }
                    break;
                }
                for(int i = 0 ;i<newstitle.size();i++){
                    hreflist.add(i,newstitle.get(i).attr("href"));
                }
                writeOutHref();
                refreshableView.finishRefreshing();
            }
        }, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ps = position;
                startActivity(intent);
            }
        });
    }

    private ArrayList<String> readInMessage(){
        ArrayList<String> arr1;
        try {
            fis = new ObjectInputStream(new FileInputStream(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME + ".txt"));
        } catch (IOException e) {
            return new ArrayList();
        }
        try {
            arr1 = (ArrayList<String>)fis.readObject();
            fis.close();
            return arr1;
        } catch (ClassNotFoundException e) {
            return new ArrayList();
        } catch (IOException e) {
            return new ArrayList();
        }
    }


    private void writeOutMessage(){
        try {
            fos = new ObjectOutputStream(new FileOutputStream(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME + ".txt"));
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos.writeObject(list);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void CreateMessageText() throws IOException {
        /*String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }*/

        /*String filenameTemp = "data" + "//"+ FILE_NAME + ".txt";*/
        File file = new File(File.separator + "mnt" + File.separator + "sdcard" + File.separator);
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
            }
        }
        File dir = new File(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME + ".txt");
        if (!dir.exists()) {
            try {
                //在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
            }
        }

    }


    //超链接有关的文件
    private ArrayList<String> readInHref(){
        ArrayList<String> arr1;
        try {
            fis1 = new ObjectInputStream(new FileInputStream(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME2 + ".txt"));
        } catch (IOException e) {
            return new ArrayList<>();
        }
        try {
            arr1 = (ArrayList<String>)fis1.readObject();
            fis1.close();
            return arr1;
        } catch (ClassNotFoundException e) {
            return new ArrayList<>();
        } catch (IOException e) {
            return new ArrayList<>();
        }
    }

    private void writeOutHref(){
        try {
            fos2 = new ObjectOutputStream(new FileOutputStream(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME2 + ".txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos2.writeObject(hreflist);
            fos2.flush();
            fos2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void CreateHrefText() throws IOException {
        File file = new File(File.separator + "mnt" + File.separator + "sdcard" + File.separator);
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
            }
        }
        File dir = new File(File.separator + "mnt" + File.separator + "sdcard" + File.separator + FILE_NAME2 + ".txt");
        if (!dir.exists()) {
            try {
                //在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
            }
        }

    }

    protected void dialog(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
        dialog.setMessage("确定退出吗");
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveButton("确定",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MainActivity.this.finish();
            }
        });
        dialog.create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
            dialog();
        }
        return false;
    }
}
